﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MySqlX.XDevAPI.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.Goods;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Request.Merchant;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Goods;
using XuanXiang.Infrastructure.Dto.Response.Home;
using XuanXiang.Infrastructure.Dto.Response.Merchant;
using XuanXiang.Infrastructure.Dto.Response.Supplier;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.EFCore;
using XuanXiang.Service.Interface;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class Home_Service : Base_Service, I_Home_Service
    {
        private readonly Goods_IOC _goods_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Merchant_IOC _merchant_IOC;
        private readonly Supplier_IOC _supplier_IOC;

        public Home_Service(Goods_IOC goods_IOC,
            Merchant_IOC merchant_IOC,
            Sys_IOC sys_IOC,
            Supplier_IOC supplier_IOC)
        {
            _goods_IOC = goods_IOC;
            _sys_IOC = sys_IOC;
            _merchant_IOC = merchant_IOC;
            _supplier_IOC = supplier_IOC;
        }

        /// <summary>
        /// 获取首页的数据统计
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> GetHomeStatistics()
        {
            HomeStatistics_Dto data = new HomeStatistics_Dto();
            DateTime today = DateTime.Today;
            DateTime tomorrow = today.AddDays(1);
            //订单数据
            var allOrder = await _merchant_IOC._orders_EFCore.GetAll().ToListAsync();
            //今日订单数
            data.todayOrderCount = allOrder.Where(d => d.OcreateTime > today && d.OcreateTime < tomorrow).Count();
            //待处理的订单数
            data.undisposedOrderCount = allOrder.Where(d => d.OisAccept == -1).Count();

            //销售数据
            //今日销售额
            data.todaySalesMoney = (double?)Math.Round(
                allOrder.Where(d => d.OcreateTime > today && d.OcreateTime < tomorrow)
                        .Sum(d => (double)d.OcurrMoney!), // 先将金额转换为 double
                2
            );

            // 本周销售额：转换为 double? 并保留两位小数
            DateTime monday = today.AddDays(-(int)today.DayOfWeek + 1);
            DateTime sunday = monday.AddDays(6);
            data.weekSalesMoney = (double?)Math.Round(
                allOrder.Where(d => d.OcreateTime > monday && d.OcreateTime < sunday)
                        .Sum(d => (double)d.OcurrMoney!), // 转换为 double 避免精度丢失
                2
            );
            //供应商数据
            var allSupplier = await _supplier_IOC._supplier_EFCore.GetAll().ToListAsync();//获取所有供应商
            //供应商总数据
            data.supplierCount = allSupplier.Count();
            //今日新增的供应商数据
            data.todayAddSupplier = allSupplier.Where(d => d.ScreatTime > today && d.ScreatTime < tomorrow).Count();
            //本周新增供应商数据
            data.weekAddSupplier = allSupplier.Where(d => d.ScreatTime > monday && d.ScreatTime < sunday).Count();

            //商户数据
            var allMerchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();//获取所有的商户
            //商户总数量
            data.merchantCount = allMerchant.Count();

            //筛选本周内的数据 + 分组统计商户订单数
            var activeMerchants = _merchant_IOC._orders_EFCore
                .GetAll(d => d.OcreateTime >= monday && d.OcreateTime <= sunday) // 筛选本周订单
                .GroupBy(d => d.Omid)                                           // 按商户 Omid 分组
                .Select(group => new                                           // 统计每个商户的订单数
                {
                    Omid = group.Key,
                    OrderCount = group.Count()
                })
                .Where(stat => stat.OrderCount >= 5)                             // 筛选订单数 > 5 的商户
                .ToList();

            //活跃商户数量
            data.activeMerchantCount = activeMerchants.Count;

            //商品数据
            var allGoods = _goods_IOC._goods_EFCore.GetAll().ToList();
            //所有商品数量
            data.goodsCount = allGoods.Count();
            //已上架的商品数量
            data.shelveGoodsCount = allGoods.Where(d => d.GisShelve == 1).Count();



            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取首页统计图数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Home_Cartogram()
        {
            Home_Cartogram_Dto data = new Home_Cartogram_Dto();
            // 今日
            var today = DateTime.Today;
            var tomorrow = today.AddDays(1);
            var timeSegmentsToday = new List<Tuple<DateTime, string>>
    {
        Tuple.Create(today.AddHours(0), "00:00"),
        Tuple.Create(today.AddHours(2), "02:00"),
        Tuple.Create(today.AddHours(4), "04:00"),
        Tuple.Create(today.AddHours(6), "06:00"),
        Tuple.Create(today.AddHours(8), "08:00"),
        Tuple.Create(today.AddHours(10), "10:00"),
        Tuple.Create(today.AddHours(12), "12:00"),
        Tuple.Create(today.AddHours(14), "14:00"),
        Tuple.Create(today.AddHours(16), "16:00"),
        Tuple.Create(today.AddHours(18), "18:00"),
        Tuple.Create(today.AddHours(20), "20:00"),
        Tuple.Create(today.AddHours(22), "22:00")
    };

            // 本周
            DateTime monday = today.AddDays(-(int)today.DayOfWeek + 1);
            DateTime sunday = monday.AddDays(6);
            var timeSegmentsWeek = new List<Tuple<DateTime, string>>();
            for (int i = 0; i < 7; i++)
            {
                DateTime currentDay = monday.AddDays(i);
                timeSegmentsWeek.Add(Tuple.Create(currentDay, currentDay.ToString("MM-dd")));
            }

            // 本月
            DateTime firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
            int daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
            var timeSegmentsMonth = new List<Tuple<DateTime, string>>();
            for (int i = 0; i < daysInMonth; i++)
            {
                DateTime currentDay = firstDayOfMonth.AddDays(i);
                timeSegmentsMonth.Add(Tuple.Create(currentDay, currentDay.ToString("MM-dd")));
            }

            var allOrders = await _merchant_IOC._orders_EFCore.GetAll().ToListAsync();

            // 今日订单统计
            var todayOrders = allOrders.Where(o => o.OcreateTime >= today && o.OcreateTime < tomorrow).ToList();
            for (int i = 0; i < timeSegmentsToday.Count; i++)
            {
                var currentTime = timeSegmentsToday[i].Item1;
                var nextTime = i < timeSegmentsToday.Count - 1
                    ? timeSegmentsToday[i + 1].Item1
                    : tomorrow;

                var segmentOrders = todayOrders.Where(o => o.OcreateTime >= currentTime && o.OcreateTime < nextTime).ToList();

                data.today.xAxis.Add(timeSegmentsToday[i].Item2);
                data.today.orderData.Add(segmentOrders.Count);
                data.today.amountData.Add(
                    Math.Round(
                        segmentOrders.Sum(o => (double?)o.OcurrMoney) ?? 0,
                        2
                    )
                );
            }

            // 本周订单统计
            var weekOrders = allOrders.Where(o => o.OcreateTime >= monday && o.OcreateTime <= sunday).ToList();
            for (int i = 0; i < timeSegmentsWeek.Count; i++)
            {
                var currentTime = timeSegmentsWeek[i].Item1;
                var nextTime = i < timeSegmentsWeek.Count - 1
                    ? timeSegmentsWeek[i + 1].Item1
                    : sunday.AddDays(1);

                var segmentOrders = weekOrders.Where(o => o.OcreateTime >= currentTime && o.OcreateTime < nextTime).ToList();

                data.week.xAxis.Add(timeSegmentsWeek[i].Item2);
                data.week.orderData.Add(segmentOrders.Count);
                data.week.amountData.Add(
                    Math.Round(
                        segmentOrders.Sum(o => (double?)o.OcurrMoney) ?? 0,
                        2
                    )
                );
            }

            // 本月订单统计
            var monthOrders = allOrders.Where(o => o.OcreateTime >= firstDayOfMonth && o.OcreateTime < firstDayOfMonth.AddMonths(1)).ToList();
            for (int i = 0; i < timeSegmentsMonth.Count; i++)
            {
                var currentTime = timeSegmentsMonth[i].Item1;
                var nextTime = i < timeSegmentsMonth.Count - 1
                    ? timeSegmentsMonth[i + 1].Item1
                    : firstDayOfMonth.AddMonths(1);

                var segmentOrders = monthOrders.Where(o => o.OcreateTime >= currentTime && o.OcreateTime < nextTime).ToList();

                data.month.xAxis.Add(timeSegmentsMonth[i].Item2);
                data.month.orderData.Add(segmentOrders.Count);
                data.month.amountData.Add(
                    Math.Round(
                        segmentOrders.Sum(o => (double?)o.OcurrMoney) ?? 0,
                        2
                    )
                );
            }
            //获取所有供应商
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            //获取所有的商户
            var merchant = _merchant_IOC._merchant_EFCore.GetAll().ToList();
            // 获取当前月份的天数（当月最后一天是几日）
            int daysInCurrentMonth = DateTime.DaysInMonth(today.Year, today.Month);

            // 近 30 天供应商和商户的新增对比相关初始化
            List<string?> days = new List<string?>();
            List<int?> supplierNewList = new List<int?>();
            List<int?> merchantNewList = new List<int?>();

            for (int i = 0; i < 30; i++)
            {
                DateTime targetDay = today.AddDays(-i);

                // 统计当天新增的供应商数量（清晰的空值处理 + 日期比较）
                int newSuppliers = supplier.Count(c =>
                    c.ScreatTime.HasValue &&  // 先判断是否有值
                    c.ScreatTime.Value.Date == targetDay.Date  // 再比较日期部分
                );

                // 统计当天新增的商户数量（清晰的空值处理 + 日期比较）
                int newMerchants = merchant.Count(c =>
                    c.MCreateTime.HasValue &&  // 先判断是否有值
                    c.MCreateTime.Value.Date == targetDay.Date  // 再比较日期部分
                );

                // 只保留日期在当月合理范围内的（比如 8 月就只保留 1 日 - 31 日的日期）
                if (targetDay.Day <= daysInCurrentMonth)
                {
                    // 提取 “日” 部分并拼接 “日” 字，如 1 日 -> "1日"，直接添加到 days 集合
                    days.Add($"{targetDay.Day}日");
                    // 记录当天新增供应商数量
                    supplierNewList.Add(newSuppliers);
                    // 记录当天新增商户数量
                    merchantNewList.Add(newMerchants);
                }
            }

            // 按时间从早到晚排序（将 30 天前到今日的顺序，调整为从今日到 30 天前展示，可根据需求决定是否反转）
            // 如果想要 1 日 ~ 30 日 这样从早到晚的顺序，就执行反转
            days.Reverse();
            supplierNewList.Reverse();
            merchantNewList.Reverse();

            // 将整理好的数据赋值给 data 对象（假设 data 有对应的属性来接收）
            data.days = days;
            data.supplierNew = supplierNewList;
            data.merchantNew = merchantNewList;
            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取top5的热销商品
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Top_Goods()
        {
            var data =await _goods_IOC._goods_EFCore.GetAll(out int total, 1, 5, false, o => o.Gsales)
                .Select(d => new Goods_Dto() {
                    id=d.Gid,
                    explain=d.Gexplain,
                    imgUrl=d.Gcover,
                    inventory=d.Ginventory,
                    isBan=d.GisBan==1?true:false,
                    isPromote=d.GisPromote,
                    specs=d.Gspecs,
                    s_id=d.GSid,
                    isShelve=d.GisShelve==1?true:false,
                    name=d.Gname,
                    photo=d.Gcover,
                    price=d.Gprice,
                    tId=d.Gtype,
                    time=d.GcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToListAsync();

            var type = _sys_IOC._sys_Dictionary_EFCore.GetAll().ToList();
            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
          
           

            var today = DateTime.Today;
            DateTime monday = today.AddDays(-(int)today.DayOfWeek + 1);
            DateTime sunday = monday.AddDays(6);
            var order=_merchant_IOC._order_Details_EFCore.GetAll().ToList();
           var goods= data.Select(d => {
                d.sales= order.Where(c => c.OdGid == d.id && c.OdCreateTime > monday && c.OdCreateTime < sunday).Count();
                d.typeName = type.Where(c => c.Did == d.tId).Select(c => c.Dname).SingleOrDefault();
                var s = supplier.Where(c => c.Sid == d.s_id);
                if (s.Any())
                {
                    d.supplierName = s.Select(d => d.Sname).Single();
                }
                else
                {
                    d.supplierName = null;
                }
                return d;
            }).OrderByDescending(d=>d.sales);

            return Get_Result(0, "ok", goods);

        }

        /// <summary>
        /// 获取采购量top10的商户
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Top_Merchant()
        {
            var data = await _merchant_IOC._merchant_EFCore.GetAll(out int total, 1, 10, false, o => o.MOrderCount)
                 .Select(d => new merchant_dto() {
                    ID=d.MId,
                    name=d.MName,
                    isActive=d.MIsActive,
                    cancelMoney=d.MCancelMoney,
                    cancelOrderCount=d.MCancelOrderCount,
                    completeOrderCount=d.MCompleteOrderCount,
                    contacts=d.MContacts,
                    currMoney=d.MCurrMoney,
                    isBan=d.MIsBan==1?true:false,
                    money=d.MMoney,
                    orderCount=d.MOrderCount,
                    time=d.MCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    
                    
                 }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取销售额top10的供应商
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Top_Supplier()
        {
            var data =await _supplier_IOC._supplier_EFCore.GetAll(
                out int total, 1, 10, false, o => o.ScurrMoney )
                .Select(d => new Supplier_Dto(){ 
                id=d.Sid,
                account=d.Saccount,
                address=d.Saddress,
                announcement=d.Sannouncement,
                isActive=d.SisActive==1?true:false,
                canceledOrderCount=d.ScancelOrderCount,
                cancelMoney=d.ScancelMoney,
                completedOrderCount=d.ScompleteOrderCount,
                isBan=d.SisBan==1?true:false,
                logo=d.Slogo,
                name=d.Sname,
                orderCount=d.SorderCount,
                photo=d.Sphoto,
                time=d.ScreatTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                totalMoney=d.Smoney,
                turnoverMoney=d.ScurrMoney
                }).ToListAsync();

            return Get_Result(0, "ok", data);
        }
    }
}
